//
//  BdpRcdViewCtrl.m
//  AccuroFit
//
//  Created by Yongfeng Li on 9/10/15.
//  Copyright (c) 2015 Nci Technology Inc. All rights reserved.
//

#import <AudioToolbox/AudioServices.h>
#import "AppDelegate.h"
#import "UIGraphView.h"
#import "BdpRcdViewCtrl.h"
#import "N_BdpData.h"
#import "UIView+Extension.h"
#define DefaultColor [UIColor colorWithRed:0.83 green:0.00 blue:0.40 alpha:1.00]

@interface BdpRcdViewCtrl ()

@end

@implementation BdpRcdViewCtrl {
  UILabel* _lblMsg;
  UIGraphView* _gViewHbdp;
  UIGraphView* _gViewLbdp;
  //BOOL _bShowHbdp;
  //CGPoint _ptViewHbdp;
  //CGPoint _ptViewLbdp;
    
  UILabel* _lblSystolicTag;
  UILabel* _lblDiastolicTag;
  UILabel* _lblHeartRateTag;
    
  UILabel* _lblDatRngTip;
  UISegmentedControl* _scDateRng;
    
  UIImageView* _ivhLine;
  UIImageView* _ivvLine;
    
  UILabel* _lblCurtSysTip;
  UILabel* _lblCurtDiaTip;
    
  UILabel* _lblCurtSysVal;
  UILabel* _lblCurtDiaVal;
    
  NSMutableArray* _pBdpData;
    
  //NSMutableArray* _values;
  NSDate* _lastDatePos;
    
  NSInteger _nDtRngIdx;
  NSDate* _dtFr;
  NSDate* _dtTo;
  
  //sync with svr
  UIButton* _btnSyncData;
  UIProgressView* _progView;
  UIActivityIndicatorView* _actView;
  
  NSURLSession* _netSession;
  //NSMutableDictionary* _dicSyncData;
  
  NSUInteger _nSyncPos;
  NSUInteger _nSyncToatalPack;
  NSUInteger _nSyncCurrentPack;
  
  BOOL _bSyncGetWgtReqst;
  BOOL _bSyncGetNotNeed;
  BOOL _bMadeRcdMark;
  BOOL _bSyncEnd;
  
  NSInteger _nBodyId;
  
  UILabel* _lblSysBldpTip;
  UILabel* _lblDiaBldpTip;
  
  BOOL _bIpad;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithWhite:0.125 alpha:0.5];
    
  CGRect frame = [[UIScreen mainScreen] bounds];
  CGFloat W = frame.size.width;
  CGFloat H = frame.size.height;
  _bIpad = H > 1000;
  
  CGFloat yPos = (H <= 480)? 60: 65;
  [self initViewCtrls: yPos scrWdt: W scrHgt:H];
    self.view.backgroundColor = [UIColor whiteColor];
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //UIImage* imgback = [pApp getImageScale:(_bIpad?@"ic-mainbkgd2@1024.png":@"ic-mainbkgd2.png") scale:(_bIpad?1.0:0.32)];
//  [self.view setBackgroundColor:[UIColor colorWithPatternImage:imgback]];
  //_bShowHbdp = YES;
  //_ptViewHbdp = _gViewHbdp.center;
  //_ptViewLbdp = _gViewLbdp.center;
    
  _nBodyId = pApp.m_bodyInfo.m_nBodyId;
  //UIImage* iProf = [pApp getImageScale:@"ic-list.png" scale: 0.4];
  //UIBarButtonItem *profButton = [[UIBarButtonItem alloc] initWithImage:iProf style:UIBarButtonItemStylePlain target:self action:@selector(mainAction:)];
  //self.navigationItem.leftBarButtonItem = leftButton;
  //self.navigationItem.rightBarButtonItem = profButton;
    
    //_values = [[NSMutableArray alloc]init];
  [self chgDateRng:_scDateRng];
  [self setLastBdpMeasData];
  
  //sync
  _progView = nil;
  _actView = nil;
  _nSyncPos = 0;
  
  NSURLSessionConfiguration* cnfgSession = [NSURLSessionConfiguration defaultSessionConfiguration];// [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier: @"HrateSync"];
  cnfgSession.timeoutIntervalForRequest = 10.0; 
  _netSession = [NSURLSession sessionWithConfiguration:cnfgSession delegate: self delegateQueue: nil];
  
  _bSyncEnd = NO;
  
//  UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
//  [btnBack setImage:[UIImage imageNamed:@"btn-left-w.png"] forState:UIControlStateNormal];//@"btn_back.png"
//  [btnBack addTarget:self action:@selector(onRtnMainPage:) forControlEvents:UIControlEventTouchUpInside];
//  
//  UIBarButtonItem* btniBack = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
//  self.navigationItem.leftBarButtonItem = btniBack;
}


- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
  _lblMsg.text = NSLocalizedString(@"No enough memory!", nil);
  AudioServicesPlaySystemSound(1112);
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    imgView.image = [UIImage imageNamed:@"ic-mainbkgd2"];
    [self.view insertSubview:imgView atIndex:0];
}

-(void) viewWillDisappear:(BOOL)animated
{
  [_netSession invalidateAndCancel];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void) initViewCtrls:(CGFloat) yPos scrWdt:(CGFloat) W scrHgt:(CGFloat)H
{
    BOOL bIpad = H > 1000;
    BOOL bWider = W > 320;
    BOOL bIp4s = H <= 480;
    
    _lblMsg = [[UILabel alloc] initWithFrame:CGRectMake(20, yPos, W-40, 25)];
    _lblMsg.textColor = DefaultColor;
    _lblMsg.font = [UIFont fontWithName:@"Calibri" size:16.0];
    _lblMsg.backgroundColor = [UIColor clearColor];
    _lblMsg.textAlignment = NSTextAlignmentCenter;
    _lblMsg.text = NSLocalizedString(@"Blood Pressure", nil);
    [self.view addSubview:_lblMsg];
    
    //graph
   CGFloat yyPos = yPos + 40 + (bIpad?10:(bWider?5:1));
  _lblSysBldpTip = [[UILabel alloc] initWithFrame:CGRectMake(43, yyPos - 23, W-100, 25)];
  _lblSysBldpTip.textColor = DefaultColor;
  _lblSysBldpTip.font = Bold(16);
  _lblSysBldpTip.backgroundColor = [UIColor clearColor];
  _lblSysBldpTip.textAlignment = NSTextAlignmentLeft;
  _lblSysBldpTip.text = NSLocalizedString(@"Systolic", nil);
  [self.view addSubview:_lblSysBldpTip];
                    
    CGFloat fGhgt = H * 2 / 5 - 55;
    CGRect chartFrame  = CGRectMake(5, yyPos, W-10, fGhgt);
    _gViewHbdp = [[UIGraphView alloc] initWithFrame: chartFrame];
    _gViewHbdp.center = CGPointMake(chartFrame.size.width/2.0, chartFrame.size.height/2);
    _gViewHbdp.delegate = self;
    _gViewHbdp.dataSource = self;
    _gViewHbdp.barShadowOffset = CGSizeMake(2.0, 1.0);
    _gViewHbdp.animationDuration = 0.0;
    _gViewHbdp.barShadowColor	 = [UIColor grayColor];
    _gViewHbdp.barShadowAlpha	 = 0.5;
    _gViewHbdp.barShadowRadius = 1.0;
    //_gView.barWidth = (W-10) / 9;//chartFrame.size.width / 10.0;
    _gViewHbdp.xLabelType	 = GraphViewXLabelTypeHorizontal;
    //_gView.incrementValue = 50;
    _gViewHbdp.barTextType = GraphViewBarTextTypeTop;
    _gViewHbdp.barTextColor = [UIColor whiteColor];
    _gViewHbdp.gridColor = [UIColor grayColor];
    //_gView.backgroundColor = [UIColor grayColor];
    _gViewHbdp.frame = chartFrame;
    _gViewHbdp.nSetUnit = 201;
    [self.view addSubview:_gViewHbdp];
  
  chartFrame.origin.y += H / 3 + 5;
  _lblDiaBldpTip = [[UILabel alloc] initWithFrame:CGRectMake(43, chartFrame.origin.y - 25, W-100, 25)];
  _lblDiaBldpTip.textColor = DefaultColor;
  _lblDiaBldpTip.font = Bold(16);
  _lblDiaBldpTip.backgroundColor = [UIColor clearColor];
  _lblDiaBldpTip.textAlignment = NSTextAlignmentLeft;
  _lblDiaBldpTip.text = NSLocalizedString(@"Diastolic", nil);
  [self.view addSubview:_lblDiaBldpTip];
  
  _gViewLbdp = [[UIGraphView alloc] initWithFrame: chartFrame];
  _gViewLbdp.center = CGPointMake(chartFrame.size.width/2.0, chartFrame.size.height/2);
  _gViewLbdp.delegate = self;
  _gViewLbdp.dataSource = self;
  _gViewLbdp.barShadowOffset = CGSizeMake(2.0, 1.0);
  _gViewLbdp.animationDuration = 0.0;
  _gViewLbdp.barShadowColor	 = [UIColor grayColor];
  _gViewLbdp.barShadowAlpha	 = 0.5;
  _gViewLbdp.barShadowRadius = 1.0;
  //_gView.barWidth = (W-10) / 9;//chartFrame.size.width / 10.0;
  _gViewLbdp.xLabelType	 = GraphViewXLabelTypeHorizontal;
  //_gView.incrementValue = 50;
  _gViewLbdp.barTextType = GraphViewBarTextTypeTop;
  _gViewLbdp.barTextColor = DefaultColor;
  _gViewLbdp.gridColor = [UIColor grayColor];
  //_gView.backgroundColor = [UIColor grayColor];
  _gViewLbdp.frame = chartFrame;
  _gViewLbdp.nSetUnit = 202;
  [self.view addSubview:_gViewLbdp];
  //_gViewLbdp.hidden = YES;
    
    
    //tag tip
    /*yyPos = _gViewHbdp.frame.origin.y + _gViewHbdp.frame.size.height - 20;
    _lblSystolicTag = [[UILabel alloc] initWithFrame:CGRectMake(W/15, yyPos, W/4, 25)];
    _lblSystolicTag.textColor = [UIColor blueColor];
    _lblSystolicTag.font = [UIFont systemFontOfSize:bIpad?16.0:14.0];
    _lblSystolicTag.backgroundColor = [UIColor clearColor];
    _lblSystolicTag.textAlignment = NSTextAlignmentCenter;
    _lblSystolicTag.text =  bIpad?@"____ Systolic":@"__Systolic";
    [self.view addSubview:_lblSystolicTag];
    
    _lblDiastolicTag = [[UILabel alloc] initWithFrame:CGRectMake(W* 6 / 15, yyPos, W/4, 25)];
    _lblDiastolicTag.textColor = [UIColor redColor];
    _lblDiastolicTag.font = [UIFont systemFontOfSize:bIpad?16.0:14.0];
    _lblDiastolicTag.backgroundColor = [UIColor clearColor];
    _lblDiastolicTag.textAlignment = NSTextAlignmentCenter;
    _lblDiastolicTag.text = bIpad?@"____ Diastolic":@"__Diastolic";
    [self.view addSubview:_lblDiastolicTag];
    
    _lblHeartRateTag = [[UILabel alloc] initWithFrame:CGRectMake(W* 11 / 15, yyPos, W/4, 25)];
    _lblHeartRateTag.textColor = [UIColor greenColor];
    _lblHeartRateTag.font = [UIFont systemFontOfSize:bIpad?16.0:14.0];
    _lblHeartRateTag.backgroundColor = [UIColor clearColor];
    _lblHeartRateTag.textAlignment = NSTextAlignmentCenter;
    _lblHeartRateTag.text = bIpad?@"o Heart rate":@"o H-Rate";
    [self.view addSubview:_lblHeartRateTag];*/
    
    //date rng
  CGFloat xPos = bIpad? 100: bWider? 80:65;
  yyPos = _gViewHbdp.frame.origin.y + _gViewHbdp.frame.size.height + (bIpad?30:10) + H * 2 / 5 - 60;
  if(bIp4s)
    yyPos += 20;
  else if(!bIpad)
     yyPos += 25;
  
    _lblDatRngTip = [[UILabel alloc] initWithFrame:CGRectMake(5, yyPos, xPos - 5, 30)];
    _lblDatRngTip.textColor = DefaultColor;
    _lblDatRngTip.font = Regular(16);
    _lblDatRngTip.backgroundColor = [UIColor clearColor];
    _lblDatRngTip.textAlignment = NSTextAlignmentCenter;
//    _lblDatRngTip.text = @"Timeline";
    [self.view addSubview:_lblDatRngTip];
  
    _scDateRng = [[UISegmentedControl alloc]initWithFrame:CGRectMake(xPos - 30, yyPos - 15, W-xPos-10, 30)];
    //UIColor* bgColor = [UIColor colorWithRed:0.98 green:0.45 blue:0.05 alpha:0.25];
    //_scDateRng. = bgColor;
    //_scDateRng.tintColor = [UIColor lightGrayColor];
    _scDateRng.tintColor = [UIColor clearColor];
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:13], NSForegroundColorAttributeName: DefaultColor};
    [_scDateRng setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:13], NSForegroundColorAttributeName: [UIColor blackColor]};
    [_scDateRng setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    
    [_scDateRng insertSegmentWithTitle:@"All" atIndex:0 animated:NO];
    [_scDateRng insertSegmentWithTitle:@"1 D" atIndex:1 animated:NO];
    [_scDateRng insertSegmentWithTitle:@"1 W" atIndex:2 animated:NO];
    [_scDateRng insertSegmentWithTitle:@"1 M" atIndex:3 animated:NO];
    //[_scDateRng insertSegmentWithTitle:@"3 M" atIndex:3 animated:NO];
    [_scDateRng insertSegmentWithTitle:@"6 M" atIndex:4 animated:NO];
    [_scDateRng insertSegmentWithTitle:@"1 Y" atIndex:5 animated:NO];
    _scDateRng.selectedSegmentIndex = 3;
    [_scDateRng addTarget: self action:@selector(chgDateRng:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_scDateRng];
  
  //sync
  xPos = W - (bIpad?82:(bIp4s?58:66));
  yyPos =  H * 7 / 8 + (bIpad?15:(bIp4s?5:10));
  UIImage* iBtn = [[UIImage imageNamed:@"btn-sync-r.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  _btnSyncData = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnSyncData.frame = CGRectMake(xPos, yyPos, bIpad?72:(bIp4s?48:56), bIpad?72:(bIp4s?48:56));
  [_btnSyncData setBackgroundImage:iBtn forState:UIControlStateNormal];
  [_btnSyncData addTarget:self action:@selector(tapStartSync:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnSyncData];
    
    //line
    /*yyPos += 15 + (bIpad?80:(bWider?50:(bIp4s?30:40)));
    CGRect rt;
    UIImage* iConh = [[UIImage imageNamed:@"ic-horline.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    CGFloat fHgt = W * iConh.size.height / iConh.size.width;
    rt.origin.x = 0;
    rt.origin.y = yyPos;//(H / 2.0) + (bIpad? 115: (bIp4s?40:(bWider?85:65)));
    rt.size.height = fHgt;
    rt.size.width = W;
    _ivhLine  = [[UIImageView alloc] initWithFrame:rt];
    [_ivhLine setImage:iConh];
    [self.view addSubview:_ivhLine];
    
    yyPos += bIpad?20:(bWider?15:(bIp4s?10:10));
    UIImage* iConv = [[UIImage imageNamed:@"ic-verline.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    rt.origin.x = W / 2.0 - fHgt / 2.0;
    rt.size.height = H -  rt.origin.y - rt.size.height - (bIpad?20:10);
    rt.size.width = fHgt;//iCon.size.width;
    rt.origin.y = rt.origin.y + (bIpad?15:(bWider?10:(bIp4s?5:7)));
    _ivvLine  = [[UIImageView alloc] initWithFrame:rt];
    [_ivvLine setImage:iConv];
    [self.view addSubview:_ivvLine];
    
    //bld tips and values
    yyPos = rt.origin.y + (bIpad?40:(bWider?10:(bIp4s?0:5)));
    _lblCurtSysTip = [[UILabel alloc] initWithFrame:CGRectMake(W / 12, yyPos, W * 2 / 5, 25)];
    _lblCurtSysTip.textColor = [UIColor lightGrayColor];
    _lblCurtSysTip.font = [UIFont systemFontOfSize:bIp4s?14:16.0];
    _lblCurtSysTip.backgroundColor = [UIColor clearColor];
    _lblCurtSysTip.textAlignment = NSTextAlignmentCenter;
    _lblCurtSysTip.text = @"Current Systolic";
    [self.view addSubview:_lblCurtSysTip];
    
    _lblCurtDiaTip = [[UILabel alloc] initWithFrame:CGRectMake(W * 7 /12, yyPos, W* 2/5, 25)];
    _lblCurtDiaTip.textColor = [UIColor lightGrayColor];
    _lblCurtDiaTip.font = [UIFont systemFontOfSize:bIp4s?14:16.0];
    _lblCurtDiaTip.backgroundColor = [UIColor clearColor];
    _lblCurtDiaTip.textAlignment = NSTextAlignmentCenter;
    _lblCurtDiaTip.text = @"Current Diastolic";
    [self.view addSubview:_lblCurtDiaTip];
    
     yyPos += bIpad?50:(bWider?30:(bIp4s?12:20));
    _lblCurtSysVal = [[UILabel alloc] initWithFrame:CGRectMake(W / 12, yyPos, W * 2 / 5, 50)];
    _lblCurtSysVal.textColor = [UIColor whiteColor];
    _lblCurtSysVal.font = [UIFont boldSystemFontOfSize:bIpad?56.0:36];
    _lblCurtSysVal.backgroundColor = [UIColor clearColor];
    _lblCurtSysVal.textAlignment = NSTextAlignmentCenter;
    _lblCurtSysVal.text = @"118";
    [self.view addSubview:_lblCurtSysVal];
    
    _lblCurtDiaVal = [[UILabel alloc] initWithFrame:CGRectMake(W * 7 / 12, yyPos, W * 2 / 5, 50)];
    _lblCurtDiaVal.textColor = [UIColor whiteColor];
    _lblCurtDiaVal.font = [UIFont boldSystemFontOfSize:bIpad?56.0:36];
    _lblCurtDiaVal.backgroundColor = [UIColor clearColor];
    _lblCurtDiaVal.textAlignment = NSTextAlignmentCenter;
    _lblCurtDiaVal.text = @"76";
    [self.view addSubview:_lblCurtDiaVal];*/
}

- (void) setLastBdpMeasData
{ 
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    //bldp
    short nHpres = 0, nLpres = 0;
    NSMutableArray* pData = [NSMutableArray arrayWithArray:[pApp loadBdpData:pApp.m_bodyInfo.m_nBodyId from:nil to:nil sort:YES last:YES]];
    if(pData != nil && pData.count >0) {
        N_BdpData* pBldp = (N_BdpData*)[pData objectAtIndex:0];
        nHpres = pBldp.bphVal.shortValue;
        nLpres = pBldp.bplVal.shortValue;
    }
    _lblCurtSysVal.text = (nHpres>0)?[NSString stringWithFormat:@"%d", nHpres]:@"---";
    _lblCurtDiaVal.text = (nLpres>0)?[NSString stringWithFormat:@"%d", nLpres]:@"---";
    
}

-(void)mainAction:(id)sender  
{  
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp enterPageWithRes:@"bodyProfViewCtrl"];
}

- (NSTimeInterval) getTimeOffset:(NSInteger)nRngIdx
{
    NSTimeInterval dtInterval = _OneDaySeconds;
    //dtInterval = dtInterval * 6.0  +  dtInterval * nRngIdx * 7;
    if(nRngIdx == 1)
        dtInterval *= 1;
    else if(nRngIdx == 2)
        dtInterval *= 6;
    else if(nRngIdx == 3)
        dtInterval *= 30;
    else if(nRngIdx == 4)
        dtInterval *= 183;
    else if(nRngIdx == 5)
        dtInterval *= 365;
    
    dtInterval = -dtInterval;
    
    return dtInterval;
}

-(void) chgDateRng:(id)sender
{
    //[_values removeAllObjects];
    if(sender != nil)
        _nDtRngIdx = _scDateRng.selectedSegmentIndex;
    else
        _nDtRngIdx = 0;

    //date rng
    [_pBdpData removeAllObjects];
    NSTimeInterval dtInterval = [self getTimeOffset:_nDtRngIdx];
    _dtFr = [[NSDate date] dateByAddingTimeInterval:dtInterval];
    _dtTo = [[NSDate date] dateByAddingTimeInterval:_OneDaySeconds];
    
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if(_nDtRngIdx == 0)
        _pBdpData = [NSMutableArray arrayWithArray:[pApp loadBdpData:pApp.m_bodyInfo.m_nBodyId from:nil to:nil sort:YES last:NO]];
    else
        _pBdpData = [NSMutableArray arrayWithArray:[pApp loadBdpData:pApp.m_bodyInfo.m_nBodyId from:_dtFr to:_dtTo sort:YES last:NO]];
    [self showBdpData:_pBdpData];
    
    //_lblMsg.text = @"Date rng chged";
    AudioServicesPlaySystemSound(1109);
}

//move for fat view
/*- (void) moveOutForNextOne:(UIGraphView *)pView
{
  pView.hidden = YES;
  if(pView == _gViewHbdp) {
    _bShowHbdp = NO;        
    _gViewLbdp.hidden = NO;
    _gViewLbdp.center = _ptViewLbdp;
    _lblMsg.text = @"DIA Data";
  }
  else {
    _bShowHbdp = YES;
    _lblMsg.text = @"SYS Data";
    _gViewHbdp.hidden = NO;
    _gViewHbdp.center = _ptViewHbdp;
  }
  [self chgDateRng:_scDateRng];
}*/

- (void) setBdpInitData
{
  if(_pBdpData.count == 0)
    return;
  
  N_BdpData* firstObj = (N_BdpData *)[_pBdpData firstObject];
  NSDate* dtStart = firstObj.measDate;
  _lastDatePos = [dtStart dateByAddingTimeInterval:0];//-_OneDaySeconds];
}


- (void) showBdpData:(NSMutableArray*)pBdpData
{
  NSUInteger nCount = pBdpData.count;
   AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(nCount == 0) {
    //NSString* sTitle = [NSString stringWithFormat:@"On Rng., No data for %@ %@.", pApp.m_bodyInfo.sFirst, pApp.m_bodyInfo.sLast];
      NSString *sTitle = NSLocalizedString(@"No Data", nil);
    _lblMsg.text = sTitle;
    [ _gViewHbdp reloadDataWithColor:nil];
    [ _gViewLbdp reloadDataWithColor:nil];
    return;
  }
  
  if(!_bSyncEnd) {
    NSString* sTitle =  [NSString stringWithFormat:@"Blood Pressure for %@ %@", pApp.m_bodyInfo.sFirst, pApp.m_bodyInfo.sLast];
    _lblMsg.text = sTitle;
  }
  //_lblMsg.text = @"Blood Pressure:";
  [self setBdpInitData];
    /*AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
    NSDateFormatter* _dtFmt = pApp.dtFmt;
    [_dtFmt setDateFormat:@"MM/dd/yy"];

    NSDate* dtStart = nil;
    N_BdpData* firstObj = (N_BdpData *)[pBdpData firstObject];
    if(dtStart == nil) {
      dtStart = firstObj.measDate;
      if(dtStart == nil)
        dtStart = [NSDate date];
    }
    
    nCount = 0;
    float dAvgValPresh = 0.0, dAvgValPresl = 0.0, dAvgValHrate = 0.0;
    NSString* sDate= [_dtFmt stringFromDate:firstObj.measDate];
    
    N_BdpData *lastData = nil;//firstObj;
    _lastDatePos = [dtStart dateByAddingTimeInterval:-_OneDaySeconds];
    
    NSUInteger nMax = pBdpData.count;
    for(NSUInteger i=0; i<nMax; i++) {
      N_BdpData *nBdpData = (N_BdpData *)[pBdpData objectAtIndex:i];
      NSString* sMeasDate = [_dtFmt stringFromDate:nBdpData.measDate];
      if(sMeasDate == nil)
        continue;
      
        //NSDate* dtMeas = nBdpData.measDate;
        if([sMeasDate isEqualToString:sDate]) {
            dAvgValPresh += [nBdpData.bphVal intValue];
            dAvgValPresl += [nBdpData.bplVal intValue];
            dAvgValHrate += [nBdpData.hRate intValue];
            nCount++;
        }
        else if(i > 0) {
            lastData = (N_BdpData *)[pBdpData objectAtIndex:i-1];
            [self formNewBdpData:lastData sumh:dAvgValPresh suml:dAvgValPresl pul:dAvgValHrate count:nCount];
            
            nCount = 1;
            dAvgValPresh = [nBdpData.bphVal intValue];
            dAvgValPresl = [nBdpData.bplVal intValue];
            dAvgValHrate = [nBdpData.hRate intValue];
            sDate = [NSString stringWithString:sMeasDate];
        }
    }
    if(nMax > 0) {
        lastData = (N_BdpData *)[pBdpData objectAtIndex:nMax-1];
        [self formNewBdpData:lastData sumh:dAvgValPresh suml:dAvgValPresl pul:dAvgValHrate count:nCount];
    }   
    
    [pApp.dtFmt setDateFormat:sInitDtFmt];*/
    [_gViewHbdp reloadDataWithColor:nil];
    [_gViewLbdp reloadDataWithColor:nil];
  
  _bSyncEnd = NO;
}

/*- (void) formNewBdpData:(N_BdpData*)lastData sumh:(double)dhSum suml:(double)dlSum pul:(double)dhRate count:(NSUInteger)nCount
{_gViewHbdp
  if(_lastDatePos == nil)
    return;
  
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
    NSDateFormatter* _dtFmt = pApp.dtFmt;
    [_dtFmt setDateFormat:@"MM/dd"];
    //[_dtFmt setDateFormat:@"HH:mm:ss"];
    
    float dAvgValPresh = (nCount != 0)? dhSum/nCount:(float)[lastData.bphVal intValue];
    float dAvgValPresl = (nCount != 0)? dlSum/nCount:(float)[lastData.bplVal intValue];
    float dAvgValHrate = (nCount != 0)? dhRate/nCount:(float)[lastData.hRate intValue];
    
    BdpMeasData* newObj = [[BdpMeasData alloc] init];
    [newObj formBdpData:[_dtFmt stringFromDate:lastData.measDate] bphVal:dAvgValPresh lpres:dAvgValPresl pul:dAvgValHrate];
    double dInterval = [lastData.measDate timeIntervalSinceDate:_lastDatePos] / _DaySeconds;
    newObj.dDatePos = (float)dInterval;
    [_values addObject:newObj];
    
    [pApp.dtFmt setDateFormat:sInitDtFmt];
}*/   

//datasource and delegate
- (UIColor *)barChartColor
{
    return [UIColor blueColor];
}

- (NSUInteger)numberOfBarsInBarChart:(UIGraphView *)barChart
{
    //return 3;
    //if(_values != nil)
  if(_pBdpData != nil)
        return _pBdpData.count;
    else
        return 0;
}

- (CGFloat)barChart:(UIGraphView *)barChart valueForBarAtIndex:(NSUInteger)index
{
  if(_pBdpData == nil || _pBdpData.count <= index)
    return 0.0;
    
  /*BdpMeasData *nBdpData = (BdpMeasData *)[_values objectAtIndex:index];
  CGFloat fBdpData = nBdpData.nBphVal;
  return fBdpData;*/
  
  N_BdpData* nBdpData = (N_BdpData *)[_pBdpData objectAtIndex:index];
  CGFloat fBdpData = nBdpData.bphVal.floatValue;
  return fBdpData;
  
}

- (CGFloat)barChart:(UIGraphView *)barChart valueForBdplAtIndex:(NSUInteger)index
{
  if(_pBdpData == nil || _pBdpData.count <= index)
    return 0.0;
  
  /*BdpMeasData *nBdpData = (BdpMeasData *)[_values objectAtIndex:index];
   CGFloat fBdpData = nBdpData.nBphVal;
   return fBdpData;*/
  
  N_BdpData* nBdpData = (N_BdpData *)[_pBdpData objectAtIndex:index];
  CGFloat fBdpData = nBdpData.bplVal.floatValue;
  return fBdpData;
  
}

- (CGFloat)barChart:(UIGraphView *)barChart xposForBarAtIndex:(NSUInteger)index
{
  if(_pBdpData == nil || _pBdpData.count <= index)
    return 0.0;
  
  return index * 10;
  /*N_BdpData* nBdpData = (N_BdpData *)[_pBdpData objectAtIndex:index];
  CGFloat dInterval = [nBdpData.measDate timeIntervalSinceDate:_lastDatePos] / _DaySeconds;
  return dInterval;*/
}

- (NSString *)barChart:(UIGraphView *)barChart xLabelForBarAtIndex:(NSUInteger)index
{
  if(_pBdpData == nil || _pBdpData.count <= index)
    return @"0";
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
  NSDateFormatter* _dtFmt = pApp.dtFmt;
  if(index == 0)
    [_dtFmt setDateFormat:@"MM/dd/yyyy"];
  else
    [_dtFmt setDateFormat:@"MM/dd"];
  
  N_BdpData *nBdpData = (N_BdpData *)[_pBdpData objectAtIndex:index];
  NSString* sMeasDate = [_dtFmt stringFromDate:nBdpData.measDate];
  [_dtFmt setDateFormat:sInitDtFmt];
   
   return sMeasDate;
}

//BLP
- (UIColor *)barChart:(UIGraphView *)barChart colorForBarAtIndex:(NSUInteger)index
{
    return [UIColor greenColor];
}

- (short)barChart:(UIGraphView *)barChart lPresForBarAtIndex:(NSUInteger)index
{
  if(_pBdpData == nil || _pBdpData.count <= index)
    return 0;
  //return 100 - index * 15;
    
  //BdpMeasData *nBdpData = (BdpMeasData *)[_pBdpData objectAtIndex:index];
  //return nBdpData.nBplVal;
  N_BdpData *nBdpData = (N_BdpData *)[_pBdpData objectAtIndex:index];
  short nBdpLval = (short)nBdpData.bplVal.intValue;
  return nBdpLval;
}

- (short)barChart:(UIGraphView *)barChart hRateForBarAtIndex:(NSUInteger)index
{
  //return 25;//index * 20;
    
  //BdpMeasData *nBdpData = (BdpMeasData *)[_pBdpData objectAtIndex:index];
  //return nBdpData.nHrate;
  N_BdpData *nBdpData = (N_BdpData *)[_pBdpData objectAtIndex:index];
  short nBdpBpm = (short)nBdpData.hRate.intValue;
  return nBdpBpm;
}

- (NSString *)barChart:(UIGraphView *)barChart textForBarAtIndex:(NSUInteger)index
{
  if(_pBdpData == nil || _pBdpData.count <= index)
    return @"0";
  
  
  N_BdpData *nBdpData = (N_BdpData *)[_pBdpData objectAtIndex:index];
  short nBdpHval = (short)nBdpData.bphVal.intValue;
  NSString* sVal = [NSString stringWithFormat:@"%i", nBdpHval];
  return sVal;
}

/*- (NSString *)barChart:(UIGraphView *)barChart textForBarAtIndex:(NSUInteger)index
{
  if(_pBdpData == nil || _pBdpData.count <= index)
    return @"0";
  
  
  N_BdpData* nBdpData = (N_BdpData *)[_pBdpData objectAtIndex:index];
  CGFloat fBdpData = nBdpData.bplVal.floatValue;
  return [NSString stringWithFormat:@"%.0f", fBdpData];
  
}*/

- (NSString *)barChart:(UIGraphView *)barChart textForLdpAtIndex:(NSUInteger)index
{
  if(_pBdpData == nil || _pBdpData.count <= index)
    return @"0";
  
  
  N_BdpData* nBdpData = (N_BdpData *)[_pBdpData objectAtIndex:index];
  short nBdpLval = (short)nBdpData.bplVal.intValue;
  return [NSString stringWithFormat:@"%i", nBdpLval];
}

//sync with svr
- (void) tapStartSync:(id)sender
{
  AppDelegate* pApp = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  if(![pApp isNetWorkConnAvailable]) {
    _lblMsg.text = NSLocalizedString(@"WAN network is not Aviable!", nil);
    _lblMsg.textColor = [UIColor redColor];
    AudioServicesPlaySystemSound(1112);
    return;
  }
  
  _lblMsg.text = NSLocalizedString(@"Begin Sync Data", nil);
  //_bMadeRcdMark = NO;
  _nSyncPos = 0;
   NSInteger nBodyId = pApp.m_bodyInfo.m_nBodyId;
  _nBodyId = nBodyId;
  
  //form exists data
 _pBdpData = [NSMutableArray arrayWithArray:[pApp loadBdpData:pApp.m_bodyInfo.m_nBodyId from:nil to:nil sort:YES last:NO]];
  NSUInteger nCount = _pBdpData.count;
  //[_dicSyncData removeAllObjects];
  
  NSString* sExistIds = @"(";
  for(NSUInteger i=0; i<nCount; i++) {
    N_BdpData* pData = [_pBdpData objectAtIndex:i];
    NSString* sKey = pData.measId.stringValue;
    
    BOOL bALreadyInc = [sExistIds rangeOfString:sKey].location != NSNotFound;
    if(sKey.integerValue < 0 || bALreadyInc)
      continue;
    
    if(sExistIds.length > 1)
      sExistIds = [sExistIds stringByAppendingFormat:@",%@", sKey];
    else
      sExistIds = [sExistIds stringByAppendingFormat:@"%@", sKey];
  }
  sExistIds = [sExistIds stringByAppendingString:@")"];
  
  if(_progView == nil) {
    //CGRect frame = [[UIScreen mainScreen] bounds];
    //CGFloat W = frame.size.width;
    
    CGRect rt = _btnSyncData.frame;
    CGFloat yPos = rt.origin.y + 25;
    _progView = [[UIProgressView alloc] initWithFrame:CGRectMake(20, yPos, rt.origin.x-20, 10)];
    [self.view addSubview:_progView];
  }
  _progView.hidden = NO;
  _progView.progress = 0.0;
  
  if(_actView == nil) {
    CGRect rt = _btnSyncData.frame;
    _actView = [[UIActivityIndicatorView alloc] initWithFrame:rt];
    _actView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    _actView.hidesWhenStopped = YES;
    [self.view addSubview:_actView];
  }
  _btnSyncData.hidden = YES;
  //[NSThread detachNewThreadSelector:@selector(startActIndicator) toTarget:self withObject:nil];
  [_actView startAnimating];
  
  
  [self getBlpDataInfo:sExistIds];
}


-(void) getBlpDataInfo:(NSString*)sExistIds
{
  _lblMsg.text = NSLocalizedString(@"Sync BLP. Data...", nil);
  _nSyncPos = 0;
  _nSyncCurrentPack = 0;
  _nSyncToatalPack = 0;
  _bSyncGetWgtReqst = YES;
  
  NSString* sUrl = [NSString stringWithFormat:@"Bld?id=%ld&exist=%@&idx=%@" , (long)_nBodyId, sExistIds, @"1"];
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"DELETE" url:sUrl data:nil];
  request.timeoutInterval = 10.0;
  [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if(data == nil)
      return;
                           
    // handle response
    NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    if(sRecv.length > 10) {
      _bSyncGetNotNeed = YES;
      [self stopSyncProcess];
      return;
    }
    else if(sRecv.length == 0) {
      _lblMsg.text = NSLocalizedString(@"APP Server can not connected!", nil);
      _lblMsg.textColor = [UIColor redColor];
                             
      _nSyncToatalPack = -1;
      _bSyncGetNotNeed = YES;
      [self stopShowSyncCtrld];
      AudioServicesPlaySystemSound(1112);
      return;
    }
                           
    _nSyncToatalPack = sRecv.integerValue;
    if(_nSyncToatalPack > 0) {
      _bSyncGetNotNeed = NO;
      [self requestBlpData];
      //[self syncSendHrateData];
    }
    else {
      //_lblMsg.text = @"Not need SYNC with Download";
      //[self performSelectorOnMainThread:@selector(noSyncDownloadTip:) withObject:@"Not need SYNC with Download" waitUntilDone:NO];
      //[NSThread sleepForTimeInterval:1.0];
      _bSyncGetNotNeed = YES;
      [self stopSyncProcess];
    }
  }];
  
  /*NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
   [task resume];*/
}

- (void) stopSyncProcess
{
  _scDateRng.selectedSegmentIndex = 0;
  
  dispatch_async(dispatch_get_main_queue(), ^{
    [_netSession finishTasksAndInvalidate];
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    _pBdpData = [NSMutableArray arrayWithArray:[pApp loadBdpData:_nBodyId from:nil to:nil sort:YES last:NO]];
  });
  
  _bSyncEnd = YES;
  //[self performSelector:@selector(stopShowSyncCtrld) withObject:nil afterDelay:0.05];
  [self performSelectorOnMainThread:@selector(stopShowSyncCtrld) withObject:nil waitUntilDone:NO];
}

-(void) stopShowSyncCtrld
{  
  //dispatch_sync(dispatch_get_main_queue(), ^{
  NSString* sMsg = NSLocalizedString(@"SYNC completed!", nil);
  if(_bSyncGetNotNeed)
    sMsg = NSLocalizedString(@"BLP Data Already SYNC!", nil);
  
  //dispatch_async(dispatch_get_main_queue(), ^{
  
  // computations 
  [_actView performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:NO];
  //[_actView stopAnimating];
  
  _btnSyncData.hidden = NO;
  if(_progView != nil)
    _progView.hidden = YES;
  
  _lblMsg.text = sMsg;
  //[_lblMsg performSelectorOnMainThread:@selector(setText:) withObject:sMsg waitUntilDone:YES];
  
  [self showBdpData:_pBdpData];
  //if(_bSyncGetNotNeed)
    AudioServicesPlaySystemSound(1112);
  //});
}

- (void) requestBlpData {
  if(_nSyncPos >= _nSyncToatalPack) {
    _nSyncPos = 0;
    [self stopSyncProcess];
    return;
  }
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  NSString* sUrl = [NSString stringWithFormat:@"Bld?id=%ld", (long)_nBodyId];
  NSDictionary *measData = @{
                             @"BodyId" : [NSString stringWithFormat:@"%ld", (long)_nBodyId],
                             @"hType" : [NSString stringWithFormat:@"1"],
                             @"_nSyncPos" : [NSString stringWithFormat:@"%ld", (long)_nSyncPos]
                             };
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"PUT" url:sUrl data:measData];
  request.timeoutInterval = 10.0;
  
  
  // 6.发送连接请求
  //[NSURLConnection connectionWithRequest:request delegate:self];
  NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
  [task resume];
}


- (void) showSyncProgress
{
  if(_nSyncToatalPack > 0) {
    if(_nSyncCurrentPack >= _nSyncToatalPack)
      _lblMsg.text = NSLocalizedString(@"Wait...", nil);
    else
      //_lblMsg.text = [NSString stringWithFormat:@"SYNC %ld / %ld %@", (long)(_nSyncCurrentPack+1), (long)_nSyncToatalPack, (_bSyncGetWgtReqst?@"with Download BLP":@"with Download Fat")]; //(long)(_nSyncPos+1)];
            _lblMsg.text = NSLocalizedString(@"Downloading history data", nil);
    CGFloat fProg = (CGFloat)(_nSyncCurrentPack+1) / _nSyncToatalPack;
    _progView.progress = fProg;
  }
}

- (void) storeSyncGetBlpData:(NSData*)wData
{
  if(_nSyncPos >= _nSyncToatalPack) {
    _nSyncPos = 0;
    [self stopSyncProcess];
    return;
  }
  [self performSelectorOnMainThread:@selector(showSyncProgress) withObject:nil waitUntilDone:NO];
  
  //NSString* sRecv = [[NSString alloc] initWithData:hData encoding:NSASCIIStringEncoding];
  
  NSError *e = nil;
  NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: wData options: NSJSONReadingMutableContainers error: &e];;
  for(NSDictionary *item in jsonArray) {
    //NSLog(@"Item: %@", item);
    NSNumber* nMeasId = [item objectForKey: @"MeasId"];
    NSString* sDate = [item objectForKey:@"MeasDate"];
    
    NSNumber* nBlpHval = [item objectForKey:@"BldpHval"];
    NSNumber* nBlpLval = [item objectForKey:@"BldpLval"];
    NSNumber* nBlpBpm = [item objectForKey:@"Hrate"];
    
    [self storeSyncDownloadBlpData:nMeasId date:sDate hVal:nBlpHval lVal:nBlpLval bpm:nBlpBpm];
  }
  
  _nSyncPos++;
  [self requestBlpData];
}

- (void) storeSyncDownloadBlpData:(NSNumber*)nMeasId date:(NSString*)sDate hVal:(NSNumber*)nBlpHval lVal:(NSNumber*)nBlpLval bpm:(NSNumber*)nBlpBpm
{
  dispatch_sync(dispatch_get_main_queue(), ^{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp insertSyncBdpData:nMeasId date:sDate hVal:nBlpHval lVal:nBlpLval bpm:nBlpBpm];
  });
}


//delegate funcs
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
  //_lblMsg.text = error.description;
  if(error != nil) {
    _lblMsg.text = NSLocalizedString(@"APP Server Connection failed!", nil);
    _lblMsg.textColor = [UIColor redColor];
    [self stopSyncProcess];
    AudioServicesPlaySystemSound(1112);
  }
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
  if (data == nil) {
    [_actView stopAnimating];
    _btnSyncData.hidden = NO;
    AudioServicesPlaySystemSound(1112);
    return;
  }
  
  //BOOL bShowProg = YES;
  if(_bSyncGetWgtReqst) {
    _nSyncCurrentPack++;
    [self storeSyncGetBlpData:data];
  }
  else {
    /*NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
     sRecv = [sRecv substringWithRange: NSMakeRange(1, sRecv.length-2)];
     if([sRecv hasPrefix:@"Ready"]) {
     if([self sendWgtData])
     _nSyncCurrentPack++;
     
     _nSyncPos++;
     }
     else {
     [self stopSyncProcess];
     }*/
    [self stopSyncProcess];
  }
  //if(bShowProg)
  //[self performSelectorOnMainThread:@selector(showSyncProgress) withObject:nil waitUntilDone:NO];
}

@end
